<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <span>
          <span>{{channelColumnConfig.channelName}}</span>
          <span v-if="channelColumnConfig.columnName"> > </span>
          <span>{{channelColumnConfig.columnName}}</span>
        </span>
        <el-button
                type="primary"
                size="mini"
                @click="handleAddMediaFromPackage"
                :disabled="!channelColumnConfig.columnSelected">
          <el-icon>
            <plus />
          </el-icon>
          从媒资包添加
        </el-button>
      </div>
    </template>
    <el-row>
      <el-col :span="20">
        <el-select
          placeholder="选择媒资类型"
          v-model="queryList.mediatype"
          size="mini"
          clearable
          class="input-w mr10"
          @change="handleFilterMedia"
        >
          <el-option
                  v-for="type in mediatypeList"
                  :key="type.mediatype"
                  :label="type.name"
                  :value="type.mediatype"
          />
        </el-select>
        <el-input
                placeholder="请输入媒资名称"
                v-model="queryList.keyword"
                size="mini"
                class="input-w mr10"
                clearable
                @clear="handleFilterMedia"
                @keyup.enter="handleFilterMedia"
        />
        <el-button type="primary" size="mini" @click="handleFilterMedia">
          <el-icon>
            <search />
          </el-icon>
          搜索
        </el-button>
      </el-col>
      <el-col :span="4">
        <div align="right">
          <el-button type="danger" size="mini" :disabled="!channelColumnConfig.columnSelected" @click="handleBatchDeleteMedias">
            <el-icon>
              <delete />
            </el-icon>
            移除
          </el-button>
        </div>
      </el-col>
      <el-col :span="24" class="mt10">
        <el-table
                ref="columnMediaRef"
                :data="tableData.listData"
                v-loading="isloading"
                border
                style="width: 100%"
                max-height="350"
                @row-click="handleRowClick"
                @select="handleSelect"
                @select-all="handleSelectAll"
        >
          <el-table-column type="selection" width="50" :selectable="handleSelectable"/>
          <el-table-column label="缩略图" width="80">
            <template #default="{row, $index}">
              <span @click.stop>
                <el-image
                        v-if="row.thumbs && row.thumbs.length > 0"
                        :src="row.thumbs[0].isself == 1 ? row.thumbs[0].viewurl + '&width=60px' : row.thumbs[0].viewurl"
                        :preview-src-list="imgSrcList"
                        :initial-index="$index"
                />
              </span>
            </template>
          </el-table-column>
          <el-table-column label="媒资ID" prop="mediaid" />
          <el-table-column label="媒资名称" prop="name" show-overflow-tooltip />
          <el-table-column label="媒资类型" prop="mediatypename" />
          <el-table-column label="一级分类" prop="catname"></el-table-column>
          <el-table-column label="操作" fixed="right" width="80" v-if="channelColumnConfig.columnSelected">
            <template #default="{row}">
              <el-button type="text" size="mini" :style="{color: (row.rel && row.rel.corpid == currentCorpid) ? 'red' : ''}" :disabled="!row.rel || row.rel.corpid != currentCorpid" @click.stop="handleDeleteMedia(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="24" class="mt10">
        <table-pagination
                :query-list="queryList"
                :total="tableData.total"
                @pagination="getMediaList"
        />
      </el-col>
    </el-row>
  </el-card>
  <project-package-media
          ref="projectPackageMediaRef"
          :packageid="query.packageid"
          :columnid="columnid"
          :dialog-visible="dialogVisible"
          :media-type-list="mediatypeList"
          @handleCancelDialog="handleCancelDialog"
          @reloadColumnMedias="getMediaList"
  />
</template>

<script>
  import {reactive, ref, nextTick} from 'vue'
  import {Search, Delete, Plus} from '@element-plus/icons'
  import {getMediaTYpe} from "@/api/media/mediatype";
  import {getPackageChannelMedias, getPackageColumnMedias, deleteColumnRelMedia} from "@/api/package/package";
  import TablePagination from "@/views/public/TablePagination";
  import ProjectPackageMedia from "./ProjectPackageMedia";
  import {ElMessage, ElMessageBox} from 'element-plus'

  export default {
    name: "ChannelColumnMedia",
    components: {Search, Delete, Plus, TablePagination, ProjectPackageMedia},
    props: {
      channelColumnConfig: {
        type: Object,
        default() {
          return {
            channelid: undefined,
            channelName: undefined,
            columnid: undefined,
            columnName: undefined
          }
        }
      },
      query: {
        type: Object,
        default() {
          return {
            packageid: undefined
          }
        }
      },
      currentCorpid: {
        type: Number,
        required: true
      }
    },
    setup(props) {
      const isloading = ref(false)
      const queryList = reactive({
        page: 1,
        pagesize: 25,
        ifext: 1,
        channelid: undefined,
        columnid: undefined,
        packageid: undefined,
        keyword: undefined,
        mediatype: undefined
      })
      const tableData = reactive({
        total: 0,
        listData: []
      })
      const mediatypeList = ref([])
      const mediatypeObj = reactive({})
      const imgSrcList = ref([])
      const formData = reactive({
        columnid: undefined,
        packageid: undefined,
        ifext: 1,
        mediaids: []
      })
      /** 从内容包选择媒资相关参数开始 **/
      const dialogVisible = ref(false)
      const columnid = ref(0)
      const projectPackageMediaRef = ref(null)
      /** 从内容包选择媒资相关参数结束 **/
      const columnMediaRef = ref(null)

      /** 获取频道媒资列表 **/
      const getChannelMediaList = () => {
        isloading.value = true
        queryList.channelid = props.channelColumnConfig.channelid
        queryList.columnid = undefined
        queryList.packageid = props.query.packageid
        getPackageChannelMedias(queryList).then(response => {
          isloading.value = false
          if (response.errcode == 0) {
            const {total, list} = response.data
            tableData.listData = list
            tableData.total = total
            getMediaThumbList()
          }
        })
      }
      /** 获取栏目媒资列表 **/
      const getChannelColumnMediaList = () => {
        isloading.value = true
        queryList.channelid = props.channelColumnConfig.channelid
        queryList.columnid = props.channelColumnConfig.columnid
        queryList.packageid = props.query.packageid
        formData.mediaids = []
        getPackageColumnMedias(queryList).then(response => {
          isloading.value = false
          if (response.errcode == 0) {
            const {total, list} = response.data
            tableData.listData = list
            tableData.total = total
            getMediaThumbList()
          }
        })
      }
      /** 获取媒资类型列表 **/
      const getMediatypeList = () => {
        getMediaTYpe().then(response => {
          if (response.errcode == 0) {
            mediatypeList.value = response.data
            mediatypeList.value.forEach(row => {
              mediatypeObj[row.mediatype] = row.name
            })
          }
        })
      }
      /** 搜索媒资 **/
      const handleFilterMedia = () => {
        queryList.page = 1
        getMediaList()
      }
      /**获取媒资列表**/
      const getMediaList = () => {
        if (props.channelColumnConfig.columnid == undefined) {
          getChannelMediaList()
        } else {
          getChannelColumnMediaList()
        }
      }
      /** 获取媒资封面图列表 **/
      const getMediaThumbList = () => {
        imgSrcList.value = []
        nextTick(() => {
          tableData.listData.forEach(row => {
            if (row.thumbs && row.thumbs.length > 0) {
              imgSrcList.value.push(row.thumbs[0].viewurl)
            } else {
              imgSrcList.value.push('')
            }
          })
        })
      }
      /** 媒资是否可选 **/
      const handleSelectable = (row) => {
        if (!props.channelColumnConfig.columnSelected) {
          return false
        } else {
          if (!row.rel) {
            return false
          } else {
            return row.rel.corpid == props.currentCorpid
          }
        }
      }
      /** 从内容包中选择媒资 **/
      const handleAddMediaFromPackage = () => {
        columnid.value = props.channelColumnConfig.columnid
        dialogVisible.value = true
        nextTick(() => {
          projectPackageMediaRef.value.init()
        })
      }
      /** 关闭弹框 **/
      const handleCancelDialog = () => {
        dialogVisible.value = false
      }
      /** 点击行选择媒资 **/
      const handleRowClick = (row) => {
        if (props.channelColumnConfig.columnSelected && row.rel.corpid == props.currentCorpid) {
          handleSelectedMediaIds(row)
          if (formData.mediaids.includes(row.mediaid)) {
            columnMediaRef.value.toggleRowSelection(row, true)
          } else {
            columnMediaRef.value.toggleRowSelection(row, false)
          }
        }
      }
      /** 单选媒资 **/
      const handleSelect = (selection, row) => {
        handleSelectedMediaIds(row);
      }
      /** 全选媒资 **/
      const handleSelectAll = (selection) => {
        if (selection.length > 0) {
          selection.forEach(row => {
            if (!formData.mediaids.includes(row.mediaid)) {
              formData.mediaids.push(row.mediaid)
            }
          })
        } else {
          formData.mediaids = []
        }
      }
      /** 获取选择的媒资ID列表 **/
      const handleSelectedMediaIds = (row) => {
        if (!formData.mediaids.includes(row.mediaid)) {
          formData.mediaids.push(row.mediaid)
        } else {
          const index = formData.mediaids.findIndex(d => d == row.mediaid)
          formData.mediaids.splice(index, 1)
        }
      }
      /** 单条删除媒资 **/
      const handleDeleteMedia = (row) => {
        ElMessageBox.confirm('确定要删除媒资 ' + row.name + ' 吗？', '删除媒资', {
          type: 'warning',
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          formData.mediaids = [row.mediaid]
          handleDoDeleteMedias()
        }).catch((error) => {
          console.log(error);
        })
      }
      /** 批量删除媒资 **/
      const handleBatchDeleteMedias = () => {
        if (formData.mediaids.length <= 0) {
          ElMessage({type: 'warning', message: '请先选择要移除的媒资', duration: 2000})
        } else {
          ElMessageBox.confirm('已选择 ' + formData.mediaids.length + ' 条媒资， 确定要删除吗？', '删除栏目下媒资', {
            type: 'warning',
            confirmButtonText: '确定',
            cancelButtonText: '取消'
          }).then(() => {
            handleDoDeleteMedias()
          }).catch(() => {})
        }
      }
      /** 提交删除媒资 **/
      const handleDoDeleteMedias = () => {
        formData.columnid = props.channelColumnConfig.columnid
        formData.packageid = props.query.packageid
        deleteColumnRelMedia(formData).then(response => {
          if (response.errcode == 0) {
            ElMessage({type: 'success', message: response.msg, duration: 2000})
            formData.mediaids = []
            getMediaList()
          }
        })
      }

      const init = () => {
        getMediatypeList()
      }
      return {
        init,
        isloading,
        queryList,
        tableData,
        mediatypeList,
        mediatypeObj,
        handleFilterMedia,
        getMediaList,
        imgSrcList,
        handleSelectable,
        handleAddMediaFromPackage,
        dialogVisible,
        handleCancelDialog,
        projectPackageMediaRef,
        columnid,
        handleDeleteMedia,
        handleBatchDeleteMedias,
        handleRowClick,
        handleSelect,
        handleSelectAll,
        columnMediaRef
      }
    }
  }
</script>


